package com.iflytek.uoamp.agent.monitor.mcagent;

import com.alibaba.fastjson.JSON;
import com.iflytek.uoamp.agent.core.sender.monitorsender.MonitorSendMethod;
import com.iflytek.uoamp.agent.core.sender.monitorsender.monitorinterface.IItem;
import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.*;
import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.*;
import com.iflytek.uoamp.agent.monitor.dump.obj.TaskPing;
import com.iflytek.uoamp.agent.monitor.find.obj.ProgramObj;
import com.iflytek.uoamp.agent.monitor.lib.LibSendObj;
import com.iflytek.uoamp.agent.monitor.sender.config.Config;
import com.iflytek.uoamp.agent.monitor.sender.interfaces.ISender;
import com.iflytek.uoamp.agent.monitor.version.MCAgentVersion;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 
 * @ClassName: SendClient
 * @Description: 发送客户端
 * @author qinanyuan
 * @date 2017年3月23日 下午3:23:01
 */
public class SendClient implements ISender {

	private MonitorSendMethod client = new MonitorSendMethod();
//	private boolean isopen = false;

	private static SendClient instance = new SendClient();
	
	public SendClient(){

	}

	public static SendClient getInstance(){
		return instance;
	}

	@Override
	public Object send(IItem item) {
		if (item instanceof LibSendObj) {
			try {
				client.append(((LibSendObj)item).getEvent());
				return true;
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return false;
			}
		}else if (item instanceof MonitorItemResult) {
			BMonitorRequest request = new BMonitorRequest();
			request.setBody(JSON.toJSONString(item));
			request.setUptime(((MonitorItemResult) item).getUptime());
			request.setHeaders(new HashMap<String, String>());
			try {
				Logger.getRootLogger().info(new String(request.getBody()));
				BMonitorResponse respnse = client.send(request);
				SendResponse result = new SendResponse(respnse);
				return result;
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}else if(item instanceof MonitorPluginType){
			ItemType instance = new ItemType();
			String type = ((MonitorPluginType)item).getTypes();
			instance.setType(type);
			instance.setIp(((MonitorPluginType)item).getIP());
			instance.setHeaders(new HashMap<String, String>());
			//设置MAC
			instance.setMac(MCAgentConfig.getInstance().getMonitoredPointMAC());
			//设置机房名称
			instance.setHostroom(MCAgentConfig.getInstance().getEngineRoomName());
			try {
				if(((MonitorPluginType)item).getUpdateNameList()==null){
					List<BMonitorItem> result = null;
					result = client.initMonitorItem(instance);
					List<MonitorItemConfig> monitorItems = new LinkedList<MonitorItemConfig>();
                    if(result != null){
                        for(BMonitorItem cur:result){
                            MonitorItemConfig config = MonitorItemConfig.getFromString(cur.getBody());
                            config.setHeader(cur.getHeaders());
                            monitorItems.add(config);
                        }
                    }
//					Logger.getRootLogger().info("initMonitorItem返回值（UpdateNameList==null）monitorItems============================》"+JSON.toJSONString(monitorItems));
					return monitorItems;
				}else{
					List<BMonitorItem> result;
					result = client.getMonitorItem(instance, ((MonitorPluginType)item).getUpdateNameList());
					List<MonitorItemConfig> monitorItems = new LinkedList<MonitorItemConfig>();
                    if(result != null){
                        for(BMonitorItem cur:result){
                            MonitorItemConfig config = MonitorItemConfig.getFromString(cur.getBody());
                            config.setHeader(cur.getHeaders());
                            monitorItems.add(config);
                        }
                    }

//					Logger.getRootLogger().info("initMonitorItem返回值（UpdateNameList!=null）monitorItems============================》"+JSON.toJSONString(monitorItems));
					return monitorItems;
				}
			
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}else if(item instanceof MCAgentVersion){
			try {
				return client.isUpdate(((MCAgentVersion)item).getVersion());
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}else if(item instanceof MCAgentIP){
			try {
				return client.getAllConfig(((MCAgentIP)item).getIp());
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}else if(item instanceof MCAgentLog){
			try {
				return client.log(((MCAgentLog)item).getLog());
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return false;
			}
		}else if(item instanceof TaskPing){
			try {
				return client.getAllConfig(((TaskPing)item).getPingPackage());
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}else if(item instanceof NewFileName){
			try {
				return client.downloadPlugin(((NewFileName)item).getFileName());
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}else if(item instanceof SelectAll){
			try {
				return client.getComponentList();
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}else if(item instanceof PluginType){
			try {
				return client.getPluginFileList(((PluginType)item).getTypes());
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}else if(item instanceof DownloadAgentPackage){
			try {
				return client.downloadAgentPackage();
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}else if(item instanceof GetAgentVersion){
			try {
				return client.getAgentVersionInfo();
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
				return null;
			}
		}
		return false;
	}

	@Override
	public Object sendBatch(List<IItem> item) {

		final List<ThriftFlumeEvent> objects = new ArrayList<ThriftFlumeEvent>();
		final List<BMonitorRequest> monitor_objects = new ArrayList<BMonitorRequest>();
		final List<Program> program_objects = new ArrayList<Program>();
		byte type = 0;
		for (IItem cur : item) {
			if (cur instanceof LibSendObj) {
				type = 1;
				objects.add(((LibSendObj)cur).getEvent());
			}else if(cur instanceof MonitorItemResult){
				type = 2;
				BMonitorRequest request = new BMonitorRequest();
				request.setBody(JSON.toJSONString(cur));
				request.setUptime(((MonitorItemResult) cur).getUptime());
				if(((MonitorItemResult) cur).getHeader()==null){
					request.setHeaders(new HashMap<String, String>());
				}else{
					request.setHeaders(((MonitorItemResult) cur).getHeader());
				}
				
				monitor_objects.add(request);
			}else if(cur instanceof ProgramObj){
				type = 3;
				
				Program pobj = new Program();
				pobj.setCpname(((ProgramObj)cur).getCpname());
				pobj.setIp(((ProgramObj)cur).getIp());
				pobj.setPort(((ProgramObj)cur).getPort());
				pobj.setPath(((ProgramObj)cur).getPath());
				pobj.setType(((ProgramObj)cur).getType());
				pobj.setFlags(((ProgramObj)cur).getFlags());
				pobj.setTrust(((ProgramObj)cur).getTrust());
				pobj.setHeaders(((ProgramObj)cur).getInfon());
	    		//getMAC
				pobj.setMac(MCAgentConfig.getInstance().getMonitoredPointMAC());
	    		//get机房名称
				pobj.setHostroom(MCAgentConfig.getInstance().getEngineRoomName());
				//get主机名称
				pobj.setHostname(MCAgentConfig.getInstance().getMonitoredHostName());
				
				if(pobj.getFlags()==null){
					pobj.setFlags(new LinkedList<String>());
				}
				if(pobj.getPath()==null){
					pobj.setPath("");
				}
				Logger.getRootLogger().info("will send "+ JSON.toJSONString(pobj));
				program_objects.add(pobj);
			}
		}
		try {
			if(type==1){
				client.appendBatch(objects);
			}else if(type==2){
				return new SendResponse(client.sendBatch(monitor_objects));
			}else if(type==3){
				Logger.getRootLogger().info("add services!!");
				Status temp = client.addServices(program_objects);
				return new SendResponse(temp);
			}
			return true;
		} catch (Exception e) {
			Logger.getRootLogger().error(e.getMessage(),e);
			return false;
		}
	}

	@Override
	public boolean ping() {
		try {
			String configip = MCAgentConfig.getInstance().getConfigIp();
			String findip = MCAgentConfig.getInstance().getMonitoredPointIp();
			String version = MCAgentConfig.getInstance().getSubVersion();
			String hostRoomName = MCAgentConfig.getInstance().getEngineRoomName();
			if(Status.OK == client.ping(findip + "," + hostRoomName + (char)30 + findip + "," + version)){
				return true;
			}
		} catch (Exception e) {
			Logger.getRootLogger().error("SendClient execute ping exception : ",e);
		}
//		this.isopen = false;
		return false;
	}
	
//	@Override
//	public boolean isOpen() {
//		return this.isopen;
//	}

	@Override
	public boolean close() {
//		this.transport.close();
//		this.isopen = false;
		return false;
	}

	@Override
	public boolean isOpen() {
		return true;
	}
}
